package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ServiceException;
import com.bumptech.glide.Glide;
import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.CertificationInfoBean;
import com.kpx.app.cache.FileCache;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.ResObj;
import com.kpx.app.listener.AliyunUploadListener;
import com.kpx.app.utils.AliyunFileUploader;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by congdy on 17/3/9.
 * 视频认证
 */

public class ActivityVideoCertification extends ActivityBase {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.img_video)
    ImageView imgVideo;
    @BindView(R.id.txt_mention)
    TextView txt_mention;
    @BindView(R.id.txt_fail_msg)
    TextView txt_fail_msg;
    @BindView(R.id.ll_re_try)
    LinearLayout llReTry;
    @BindView(R.id.img_to_video)
    ImageView imgToVideo;
    @BindView(R.id.ll_revedio)
    LinearLayout llRevedio;
    @BindView(R.id.ll_to_certification)
    LinearLayout llToCertification;
    @BindView(R.id.btn_uplade)
    Button btn_uplade;
    private int GET_VEDIO_BACK;
    private String path;
    private boolean isUploadSuccess = false;
    private String cloudKey;
    private CertificationInfoBean b;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_video_certification);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "视频认证");
    }

    @Override
    public void initData() {
        String[] names = {"\\*认证说明：", "\\*拍摄要点："};
        SpannableString s = new SpannableString(getResources().getString(R.string.video_certification));
        for (int i = 0; i < names.length; i++) {
            // 将名字转换为蓝色
            Pattern p = Pattern.compile(names[i]);
            Matcher m = p.matcher(s);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red_FF4088)), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        txt_mention.setText(s);
        if (getIntent().getExtras() != null) {
            b = (CertificationInfoBean) getIntent().getExtras().getSerializable(Constants.KEY_CERINFO_BEAN);
            if (b != null) {
                if (b.getVideosAuthenStatus() == 2) {
                    imgToVideo.setVisibility(View.GONE);
                    llReTry.setVisibility(View.GONE);
                    btn_uplade.setVisibility(View.VISIBLE);
                    btn_uplade.setText("审核中");
                } else if (b.getVideosAuthenStatus() == 3) {
                    txt_fail_msg.setVisibility(View.VISIBLE);
                    txt_fail_msg.setText("驳回原因：" + b.getVideosAuthenRecord().getRemark());
                }else if (b.getVideosAuthenStatus() == 1) {
                    imgToVideo.setVisibility(View.GONE);
                    llReTry.setVisibility(View.GONE);
                    btn_uplade.setVisibility(View.VISIBLE);
                    btn_uplade.setText("认证成功");
                }
            }
        }
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick({R.id.img_video, R.id.ll_revedio, R.id.ll_to_certification, R.id.img_to_video})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_video:
                if (TextUtils.isEmpty(path) || b != null) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString(getString(R.string.intent_key_vedio), path);
                Intent intent = new Intent(this, PlayVideoActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.ll_revedio:
                IntentUtil.gotoActivityForResult(this, VideoRecodeActivity.class, GET_VEDIO_BACK);
                break;
            case R.id.ll_to_certification:
                toGO();
                break;
            case R.id.img_to_video:
                if (b != null) {
                    return;
                }
                IntentUtil.gotoActivityForResult(this, VideoRecodeActivity.class, GET_VEDIO_BACK);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String tempath = (String) FileCache.sharedInstance().get(Constants.KEY_VEDIO_CHCHE);
        if (!TextUtils.isEmpty(path) && !TextUtils.isEmpty(tempath) && !path.equals(tempath)) {
            isUploadSuccess = false;
        }
        path = tempath;
        if (TextUtils.isEmpty(path)&&b!=null) {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            //获取网络视频
            retriever.setDataSource(b.getVideosAuthenRecord().getVideos(), new HashMap<String, String>());
//获取本地视频
//retriever.setDataSource(url);
            Bitmap bitmap = retriever.getFrameAtTime();
            FileOutputStream outStream = null;
            try {
                outStream = new FileOutputStream(new File(getExternalCacheDir().getAbsolutePath() + "/tem_certification_video.mp4"));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 10, outStream);
                outStream.close();
                retriever.release();
                imgVideo.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        Bitmap bitmap = getLocalVideoThumbnail(path);
        if (bitmap != null) {
            imgVideo.setImageBitmap(bitmap);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && data.getExtras() != null) {
            path = getIntent().getExtras().getString(getString(R.string.intent_key_vedio));
            if (TextUtils.isEmpty(path)) {
                return;
            }
            Bitmap bitmap = getLocalVideoThumbnail(path);
            if (bitmap != null) {
                imgVideo.setImageBitmap(bitmap);
            }
        }
    }

    private void toGO() {
        if (TextUtils.isEmpty(path)) {
            ToastUtil.getInstance().showToast(ActivityVideoCertification.this, "请先拍摄视频");
            return;
        }
        if (isUploadSuccess) {
            toCertification(cloudKey);
            return;
        }
        showLoadingDialog();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String[] date = df.format(new Date()).split("-");
        cloudKey = date[0] + date[1] + "/" + date[2] + "/" + UserInfoUtils.getCachedLoginUser().getUSER().getDmId() + StringUtil.getUniqueString() + Constants.VIDEO_FILE_SUFFIX;
        try {
            new AliyunFileUploader(path, cloudKey, UserInfoUtils.getCachedLoginUser().getACCOUNTCONFIG().getBucketone(), this, new AliyunUploadListener() {
                @Override
                public void onSuccess(String cloudKey, String sourceFilePath) {
                    dissmissLoadingDialog();
                    isUploadSuccess = true;
                    toCertification(cloudKey);
                }

                @Override
                public void onProgress(String cloudKey, long progress, long total) {
                }

                @Override
                public void onFailure(String cloudKey, ServiceException e) {
                    dissmissLoadingDialog();
                }
            }).upload();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void toCertification(String cloudKey) {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("vidoes", cloudKey);
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    ToastUtil.getInstance().showToast(ActivityVideoCertification.this, "认证提交成功");
                    FileCache.sharedInstance().put(Constants.KEY_VEDIO_CHCHE,"");
                    finish();
                } else {
                    ToastUtil.getInstance().showToast(ActivityVideoCertification.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityVideoCertification.this, error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_POST_CERTIFICATION_VEDIO, true, map);
    }

    /**
     * 获取本地视频的第一帧
     *
     * @param filePath
     * @return
     */
    public static Bitmap getLocalVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        //MediaMetadataRetriever 是android中定义好的一个类，提供了统一
        //的接口，用于从输入的媒体文件中取得帧和元数据；
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据文件路径获取缩略图
            retriever.setDataSource(filePath);
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }
}
